package com.xsj.utils;

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component // 添加此注解
public class AMapGeocoder {
    // 请替换为您自己的高德Key（控制台获取）
    private static final String KEY = "dc6d474e4bacc1d0a83262187c40cf68";
    private static final Pattern LOCATION_PATTERN =
            Pattern.compile("\"location\":\"?(\\d+\\.\\d+),(\\d+\\.\\d+)\"?");

    /**
     * 标准地址解析（必须包含省市区三级结构）
     */
    public static double[] parseStandardAddress(String fullAddress) {
        try {
            // 1. 验证地址格式
            if (!isStandardAddress(fullAddress)) {
                System.err.println("地址格式不符合要求，必须包含省市区三级结构");
                return null;
            }

            // 2. 解析地址成分
            String[] parts = parseAddressComponents(fullAddress);
            if (parts == null) return null;

            // 3. 构建请求URL
            String url = buildGeocodeUrl(parts[2], parts[1], parts[0]); // 参数顺序：详细地址、区、市

            System.out.println("[DEBUG] 请求URL: " + url);

            // 4. 发送请求并解析
            String response = sendHttpGetRequest(url);
            System.out.println("[DEBUG] API响应: " + response);

            return parseLocation(response);

        } catch (Exception e) {
            System.err.println("地理编码错误: " + e.getMessage());
            return null;
        }
    }

    /**
     * 验证是否为标准地址格式（包含省市区）
     */
    private static boolean isStandardAddress(String address) {
        return address != null &&
                address.matches(".*省.*市.*区.*") ||
                address.matches(".*市.*区.*"); // 兼容直辖市
    }

    /**
     * 解析地址成分 [0]市 [1]区 [2]详细地址
     */
    private static String[] parseAddressComponents(String fullAddress) {
        // 处理直辖市（北京、上海、天津、重庆）
        if (fullAddress.matches("(北京|上海|天津|重庆)市.*区.*")) {
            String city = fullAddress.substring(0, 2); // 提取"北京市"
            String remaining = fullAddress.substring(2);

            Matcher m = Pattern.compile("(.*?区)(.*)").matcher(remaining);
            if (m.find()) {
                return new String[]{city, m.group(1), m.group(2)};
            }
        }
        // 处理省级地址
        else {
            Matcher m = Pattern.compile("(.*?省)(.*?市)(.*?区)(.*)").matcher(fullAddress);
            if (m.find()) {
                return new String[]{m.group(2), m.group(3), m.group(4)}; // 市、区、详细地址
            }
        }
        System.err.println("无法解析地址成分: " + fullAddress);
        return null;
    }

    /**
     * 构造地理编码请求URL
     */
    private static String buildGeocodeUrl(String detail, String district, String city)
            throws UnsupportedEncodingException {
        return String.format(
                "https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s&city=%s&district=%s",
                URLEncoder.encode(detail, "UTF-8"),
                KEY,
                URLEncoder.encode(city, "UTF-8"),
                URLEncoder.encode(district, "UTF-8")
        );
    }

    /**
     * 发送HTTP GET请求
     */
    private static String sendHttpGetRequest(String url) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
    }

    /**
     * 解析经纬度
     */
    private static double[] parseLocation(String json) {
        Matcher m = LOCATION_PATTERN.matcher(json);
        if (m.find()) {
            return new double[]{
                    Double.parseDouble(m.group(1)),
                    Double.parseDouble(m.group(2))
            };
        }
        System.err.println("未找到经纬度，响应内容: " + json);
        return null;
    }

    // ==================== 测试用例 ====================
    public double[] test(String address) {
        // 标准地址测试
        double[] doubles = testStandardAddress(address);
        return doubles;
//        testStandardAddress("江苏省南京市鼓楼区北京西路2号");
//        testStandardAddress("北京市朝阳区阜通东大街6号");


    }

    private static double[] testStandardAddress(String address) {
        System.out.println("\n测试标准地址: " + address);
        double[] coord = parseStandardAddress(address);
        if (coord != null) {
            System.out.printf("解析成功 → 经度: %.6f, 纬度: %.6f\n",
                    coord[0], coord[1]);
            return coord;
        } else {
            System.out.println("解析失败（请检查地址格式或API Key）");
            return null;
        }
    }
}